import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {
  AlipayCircleOutlined,
  AlipayOutlined,
  LockOutlined,
  MobileOutlined,
  MediumOutlined,
  TaobaoOutlined,
  UserOutlined,
  WeiboCircleOutlined,
  WeiboOutlined,
} from '@ant-design/icons';
import { useIntl, history, useModel, Link } from '@umijs/max';
import { Divider, Form, message, Space, Tabs, theme } from 'antd';
import React, { useState } from 'react';
import type { CSSProperties } from 'react';
import { getCode, register, checkUsername } from '@/services/user/yonghujiekou'
import { flushSync } from 'react-dom';
import { useForm } from 'antd/es/form/Form';

const iconStyles: CSSProperties = {
  color: 'rgba(0, 0, 0, 0.2)',
  fontSize: '18px',
  verticalAlign: 'middle',
  cursor: 'pointer',
};

const Register: React.FC = () => {
  const { token } = theme.useToken();
  const [userLoginState, setUserLoginState] = useState({});
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();
  const [form] = Form.useForm();
  const [emailState, setEmailState] = useState<boolean>(false);
  const [usernameState, setUsernameState] = useState<boolean>(false);


  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };



  const registerUser = async (values: API.UserRegisterRequest) => {
    try {
      // 登录
      const res = await register({ ...values });
      if (res.code === 0) {
        message.success('注册成功！');
        history.push('/user/login')
      } else {
        message.error(res.message)
      }
    } catch (error) {
      message.error('注册失败，请重试！');
    }
  };

  const validateUsername = async () => {
    const username = form.getFieldValue('username');
    const res = await checkUsername(username);
    if (res.code != 0) {
      form.setFields([{ name: 'username', errors: [res.message ?? ''] }]);
      setUsernameState(true);
      return false
    }
    setUsernameState(false);
    return true
  };

  const validateEmail = async () => {
    const email = form.getFieldValue('email');
    const res = await checkUsername(email);
    if (res.code != 0) {
      form.setFields([{ name: 'email', errors: [res.message ?? ''] }]);
      setEmailState(true);
    }
    setEmailState(false);
    return true
  };

  const vaildEmail = (email: any) => {
    const emailPattern = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
    if (!emailPattern.test(email)) {
      message.error('邮箱格式错误！');
      return false;
    }
    return true
  }

  return (
    <div
      style={{
        backgroundColor: 'white',
        height: '100vh',
      }}
    >
      <LoginFormPage
        acti
        form={form}
        submitter={{ searchConfig: { submitText: '注册', }}}
        backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
        // logo="https://github.githubassets.com/images/modules/logos_page/Octocat.png"
        backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
        title="GroupHy"
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0,0.65)',
          backdropFilter: 'blur(4px)',
        }}
        subTitle="数据分析平台"
        onFinish={async (values: any) => {
          await registerUser(values as API.UserRegisterRequest);

        }}
        
        
        
      >
        <Tabs
          centered
          activeKey={"register"}
        >
          <Tabs.TabPane key={'register'} tab={'注册'} />
        </Tabs>
        <ProFormText
          name="username"
          fieldProps={{
            onBlur: validateUsername
          }}
          placeholder={'请输入用户名'}
          rules={[
            {
              required: true,
              message: '请输入用户名!',
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          placeholder={'请输入密码'}
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },
          ]}
        />
        <ProFormText
          name="email"
          fieldProps={{
            onBlur: validateEmail
          }}
          placeholder={'请输入邮箱'}
          rules={[
            {
              required: true,
              message: '请输入邮箱！',
            },
            {
              pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
              message: '邮箱格式错误！',
            },
          ]}
        />
        <ProFormCaptcha
          captchaProps={{
            size: 'large',
          }}
          placeholder={'请输入验证码'}
          captchaTextRender={(timing: any, count: any) => {
            if (timing) {
              return `${count} s${'获取验证码'}`;
            }
            return '获取验证码';
          }}
          name="code"
          rules={[
            {
              required: true,
              message: '请输入验证码！',
            },
          ]}
          onGetCaptcha={async () => {
            const email = form.getFieldValue('email')
            if (email === 'undefined' || !email) {
              message.error('请输入邮箱')
              return Promise.reject();
            }
            const x = vaildEmail(email)
            if (!x) {
              return Promise.reject();
            }
            if (emailState || usernameState) {
              return Promise.reject();
            }
            const y = await validateEmail()
            if (!y) {
              return Promise.reject();
            }
            const z = await validateUsername()
            if (!z) {
              return Promise.reject();
            }

            const res = await getCode(email)
            if (res.code === 0) {
              message.success('验证码发送成功！')
            } else {
              message.error('验证码发送失败！')
              return Promise.reject()
            }

          }}
        />
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >

          <Link to={'/user/login'}>去登录</Link>
        </div>
      </LoginFormPage>
    </div>
  );
};

export default () => {
  return (
    <ProConfigProvider dark>
      <Register />
    </ProConfigProvider>
  );
};
